package com.weisha.bledemo;

import java.util.Locale;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.ReaderCallback;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

import com.weisha.bledemo.adapters.TabsAdapter;
import com.weisha.bledemo.fragments.LedFragment;
import com.weisha.bledemo.fragments.NdefFragment;
import com.weisha.bledemo.fragments.SpeedTestFragment;
import com.weisha.bledemo.reader.Ntag_I2C_Demo;


@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity {
	public static Ntag_I2C_Demo demo;

	private Boolean newIntent = false;

	private TabHost mTabHost;
	private ViewPager mViewPager;
	private TabsAdapter mTabsAdapter;

	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	private NfcAdapter mAdapter;

	public final static String EXTRA_MESSAGE = "com.nxp.nfc_demo.MESSAGE";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		String languageToLoad = "en";
		Locale locale = new Locale(languageToLoad);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config,
				getBaseContext().getResources().getDisplayMetrics());

		setContentView(R.layout.activity_main);


		// Initialize the demo in order to handle tab change events
		demo = new Ntag_I2C_Demo(null, this);
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();

		mViewPager = (ViewPager) findViewById(R.id.pager);

		mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

		// mTabsAdapter.addTab(
		// mTabHost.newTabSpec("leds").setIndicator(
		// getString(R.string.leds)), LedFragment.class, null);
		//mTabsAdapter.addTab(
		//		mTabHost.newTabSpec("ndef").setIndicator(
		//				getString(R.string.ndefs)), NdefFragment.class, null);
		  mTabsAdapter.addTab(
		  mTabHost.newTabSpec("ntag_rf").setIndicator(
		  getString(R.string.ntag_rf_text)),
		  SpeedTestFragment.class, null);
		// mTabsAdapter.addTab(
		// mTabHost.newTabSpec("config").setIndicator(
		// getString(R.string.settings)), ConfigFragment.class,
		// null);

		// set current Tag to the Speedtest, so it loads the values

		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		}

		// Notifier to be used for the demo changing
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {

				if (demo.isReady()) {
					demo.FinishAllTasks();

					if (tabId.equalsIgnoreCase("leds")) {
						if (demo.isConnected())
							launchDemo(tabId);

					}
				}
				mTabsAdapter.onTabChanged(tabId);
			}
		});


		mAdapter = NfcAdapter.getDefaultAdapter(this);
		setNfcForeground();
		checkNFC();
	}

	private void checkNFC() {
		if (mAdapter != null) {
			if (!mAdapter.isEnabled()) {
				new AlertDialog.Builder(this)
						.setTitle("NFC not enabled")
						.setMessage("Go to Settings?")
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// if (android.os.Build.VERSION.SDK_INT
										// >= 16) {
										// startActivity(new
										// Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
										// } else {
										startActivity(new Intent(
												android.provider.Settings.ACTION_WIRELESS_SETTINGS));
										// }
										// startActivity(new
										// Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
									}
								})
						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										System.exit(0);
									}
								}).show();
			}
		} else {
			new AlertDialog.Builder(this)
					.setTitle("No NFC available. App is going to be closed.")
					.setNeutralButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									System.exit(0);
								}
							}).show();
		}
	}

	private ReaderCallback createReaderCallback(final Activity main) {
		return new ReaderCallback() {

			@Override
			public void onTagDiscovered(final Tag tag) {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						demo = new Ntag_I2C_Demo(tag, main);
						if (demo.isReady()) {
							String currTab = mTabHost.getCurrentTabTag();
							launchDemo(currTab);
						}
					}
				});
			}

		};
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	@Override
	public void onResume() {
		super.onResume();

		if (mAdapter != null) {
			Bundle options = new Bundle();

			if (Build.VERSION.SDK_INT >= 19) {
				// This option can be used to increase the presence check delay
				// options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY,
				// 200);
				mAdapter.enableReaderMode(this, createReaderCallback(this),
						NfcAdapter.FLAG_READER_NFC_A, Bundle.EMPTY);
			} else {
				mAdapter.enableForegroundDispatch(this, mPendingIntent,
						mFilters, mTechLists);
			}
		}
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())
				&& newIntent == false) {
			// give the UI some time to load, then execute the Demo
			final Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					onNewIntent(getIntent());
				}
			}, 100);
		}
		newIntent = false;
	}

	@SuppressLint("NewApi")
	@Override
	public void onPause() {
		super.onPause();

		if (mAdapter != null && newIntent == false) {
			if (Build.VERSION.SDK_INT >= 19)
				mAdapter.disableReaderMode(this);
			else
				mAdapter.disableForegroundDispatch(this);
		}
	}

	@Override
	protected void onNewIntent(Intent nfc_intent) {
		newIntent = true;
		super.onNewIntent(nfc_intent);
		// Set the pattern for vibration
		long pattern[] = { 0, 100 };

		// Vibrate on new Intent
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(pattern, -1);
		doProcess(nfc_intent);
	}


	public void doProcess(Intent nfc_intent) {
		final Tag tag = nfc_intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		demo = new Ntag_I2C_Demo(tag, this);
		if (demo.isReady()) {
			String currTab = mTabHost.getCurrentTabTag();
			launchDemo(currTab);
		}
	}

	private void launchDemo(String currTab) {
		// ===========================================================================
		// LED Test
		// ===========================================================================
		if (currTab.equalsIgnoreCase("leds")) {
			try {
				// if (LedFragment.getChosen()) {
				demo.LED();
			} catch (Exception e) {
				LedFragment.setAnswer(getString(R.string.Tag_lost));
			}
		}
		// ===========================================================================
		// NDEF Demo
		// ===========================================================================
		if (currTab.equalsIgnoreCase("ndef")) {
			try {
				demo.NDEF();
			} catch (Exception e) {
				// NdefFragment.setAnswer(getString(R.string.Tag_lost));
			}
		}
		// ===========================================================================
		// Config
		// ===========================================================================
		if (currTab.equalsIgnoreCase("config")) {
		}
		// ===========================================================================
		// Speedtest
		// ===========================================================================
		if (currTab.equalsIgnoreCase("ntag_rf")) {
			try {
				// SRAM Test
				if ((SpeedTestFragment.isSRamEnabled() == true)) {
					demo.SRAMSpeedtest();
				}
				// EEPROM Test
				if ((SpeedTestFragment.isSRamEnabled() == false)) {
					demo.EEPROMSpeedtest();
				} // end if eeprom test
			} catch (Exception e) {
				SpeedTestFragment.setAnswer(getString(R.string.Tag_lost));
			}
		}
	}

	public static void launchNdefDemo() {
		if (demo.isReady()) {
			if (demo.isConnected()) {
				try {
					demo.NDEF();
				} catch (Exception e) {
					NdefFragment.setAnswer("Error: Tag lost, try again");
				}
			} // else
				// NdefFragment.setAnswer("Error: No tag detected");
		}
	}

	public void setNfcForeground() {
		// Create a generic PendingIntent that will be delivered to this
		// activity. The NFC stack will fill
		// in the intent with the details of the discovered tag before
		// delivering it to this activity.
		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(
				getApplicationContext(), getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		// Setup an intent filter for all NDEF based dispatches
		mFilters = new IntentFilter[] {
		// new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED),
		new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };

		// Setup a tech list for all NFC tags
		mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
	}
}
